﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace InterFace
{
    internal class XML
    {
        /// <summary>
        /// xml序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="ob"></param>
        /// <param name="path"></param>
        public static void Serialization<T>(object ob,string path)
        {
            //声明Xml序列化对象实例serializer
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            if (!Directory.Exists(path.Substring(0, path.LastIndexOf('\\'))))
            {
                Directory.CreateDirectory(path.Substring(0, path.LastIndexOf('\\')));
            }
            //执行序列化并将序列化结果输出到控制台
            StreamWriter file = new StreamWriter(path);
            serializer.Serialize(file, ob);
            file.Close();
        }
        /// <summary>
        /// xml反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="path"></param>
        /// <returns></returns>
        public static T Deserialization<T>(string path)
        {
            T a;
            Stream s = null;
            try
            {
                XmlSerializer xs = new XmlSerializer(typeof(T));
                if (!Directory.Exists(path.Substring(0, path.LastIndexOf('\\'))))
                {
                    Directory.CreateDirectory(path.Substring(0, path.LastIndexOf('\\')));
                }
                s = new FileStream(path, FileMode.OpenOrCreate);
                a = default(T);
                if (s.Length > 0)
                {
                    a = (T)xs.Deserialize(s);
                }
                
            }
            finally
            {
                s.Close();
            }
            
            return a;
            
        }
    }
}
